from collections import OrderedDict

from django.conf import settings
from django.http import QueryDict
from django.template import Library
from django.urls import reverse

register = Library()


# @register.inclusion_tag("rbac/static_menu.html")
# def static_menu(request):
#     menu_list = request.session[settings.MOBILEDJ_MENU_SESSION_KEY]
#     return {'menu_list': menu_list}
@register.inclusion_tag("rbac/multi_menu.html")
def multi_menu(request):
    """
    二级菜单
    :param request:
    :return:
    """

    menu_dict = request.session.get(settings.MOBILEDJ_MENU_SESSION_KEY)
    key_list = sorted(menu_dict)
    ordered_dict = OrderedDict()
    for key in key_list:
        val = menu_dict[key]
        val['class'] = 'hide'
        for per in val['children']:
            if per['id'] == request.current_selected_permission:
                per['class'] = 'active'
                val['class'] = ''
        ordered_dict[key] = val
    return {'menu_dict': ordered_dict}


@register.inclusion_tag("rbac/breadcrumb.html")
def breadcrumb(request):
    return {'record_list': request.breadcrumb}


@register.filter
def has_permission(request, name):
    if name in request.session[settings.MOBILEDJ_PERMISSION_SESSION_KEY]:
        return True


@register.simple_tag
def memory_url(request, name, *args, **kwargs):
    """
    生成带有原搜索条件的url
    :param request:
    :param name:
    :return:
    """
    basic_url = reverse(name, args=args, kwargs=kwargs)
    if not request.GET:
        return basic_url
    query_dict = QueryDict(mutable=True)
    query_dict['_filter'] = request.GET.urlencode()
    old_param = query_dict.urlencode()
    return '%s?%s' % (basic_url, old_param)
